//
//  NetworTools.swift
//  Stauts
//
//  Created by Kylin on 16/3/14.
//  Copyright © 2016年 Kylin. All rights reserved.
//

import UIKit
import AFNetworking

enum RequseType : String {
    case GET = "GET"
    case POST = "POST"
}
class NetworTools: AFHTTPSessionManager {
   
    /// 给闭包起别名
    typealias Finished = (result : [String :AnyObject]? ,error : NSError?)->()
    
    // 将工具类设计成单例类
    static let shareManager : NetworTools = {
        let tools = NetworTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
}

// MARK:- 封装网络请求
extension NetworTools {
    func requst(requestType :RequseType,urlSting : String,parameters :[String : AnyObject],finished :(result : AnyObject?,error : NSError?) -> ()) {
        // 1:定义回调函数
        let successCallBack = { (task : NSURLSessionDataTask,result : AnyObject?) -> Void in
            finished(result: result, error: nil)
            
        }
        
        //2:定义失败的回调
        let failureCallBak = { (task : NSURLSessionDataTask?,error :NSError) -> Void in
            finished(result: nil, error: error)
       }
 
       // 3.根据请求方式发送请求
        if requestType == .GET {
            GET(urlSting, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBak)
        }else{
            POST(urlSting, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBak)
        }
        
    }
}

// MARK:- 请求AccessToken

extension NetworTools {
    func loadAccessToken(codeString : String,finished : Finished) {
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 2.获取请求参数
        let parameters = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : "authorization_code", "code" : codeString, "redirect_uri" : redirect_uri]
        // 3:发送请求
        requst(.POST, urlSting: urlString, parameters: parameters) { (result, error) -> () in
            finished(result: result as? [String : AnyObject], error: error)
        }
        
    }
}

// MARK:- 请求用户信息
extension NetworTools {
    
    func loadUserInfo(accessToken : String,uid : String ,finished :Finished) {
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 2.获取请求的参数
        let parameters = ["access_token" : accessToken, "uid" : uid]
        // 3.发送完了请求
        requst(.GET, urlSting: urlString, parameters: parameters) { (result, error) -> () in
            finished(result: result as? [String :AnyObject], error: error)
        }
    }
}

// MARK:- 请求微博的首页数据
extension NetworTools {
    func loadStatuses(since_id : Int, max_id : Int ,finished : (result : [[String : AnyObject]]?, error : NSError?) -> ()) {
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
         // 2.获取请求的参数
        guard let accessToken = UserAccountViewModel.shareManager.account?.access_token else {
            return
        }
        
        // 由于字典中有int类型与字符串类型所以不能进行类型推导出型
        let paramter :[String : AnyObject] = ["access_token" : accessToken,"since_id" : since_id,"max_id" : max_id]
        
        // 3:发送请求
        requst(.GET, urlSting: urlString, parameters: paramter) { (result, error) -> () in
            // 3.1.将AnyObject的结果转成字典
            guard let resultDict = result as? [String : AnyObject] else {
                finished(result: nil, error: error)
                return
            }
            
            finished(result: resultDict["statuses"] as? [[String : AnyObject]], error:error)
        }
    }
}

// MARK:- 发表微博
extension NetworTools {
    func sendstatus(statusText : String,image : UIImage? ,isSuccess : (isSuccess : Bool) -> ()) {
        // 1.获取请求的参数
        guard let accessToken = UserAccountViewModel.shareManager.account?.access_token else {
            return
        }
        
        let parameters = ["access_token" : accessToken ,"status" : statusText]
        if image == nil {
            // 2.获取请求的URLString
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            // 3:调用接口
        requst(.POST, urlSting: urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                print(error)
                isSuccess(isSuccess: false)
            }else {
                isSuccess(isSuccess: true)
            
            }
        }
            
      }else{
            // 2.获取请求的URLString
            let urlString = "https://api.weibo.com/2/statuses/upload.json"
            
             // 3.调用接口
            POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                // 3.1.将image转成NSData
                if let imageData = UIImageJPEGRepresentation(image!, 0.2) {
                    formData.appendPartWithFileData(imageData, name: "pic", fileName: "123.png", mimeType: "image/png")
                }
                
                }, progress: nil, success: { (_, result) -> Void in
                    if result != nil {
                        isSuccess(isSuccess: true)
                    }
                    
                }, failure: { (_, error) -> Void in
                    isSuccess(isSuccess: false)
            })
        }
    }
}

